<?php
/**
 * 展会管理
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/10/27
 * Time: 14:18
 */

namespace app\api\controller\activemanage;
use app\api\controller\common\ApiBase;
use app\api\model\Admin as AdminModel;
use Think\Db;
use app\api\controller\common\CommonPlus;

class Exhibition extends ApiBase
{
    protected $admin;
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        $this->model = model('Exhibition');
    }

    /**
     * 展会列表
     * @return \think\response\Json|void
     */
    public function getList()
    {
        $keyword = $this->request->param('keyword');
        $page = $this->request->param('page');
        $project_id = $this->request->param('project_id');
        $isShowExpire = $this->request->param('is_show_expire');
        $startTime = $this->request->param('start_time');
        $endTime = $this->request->param('end_time');
        //var_dump(222);die;
        $page = max(1, intval($page));
        $pagesize = empty(input('pageSize')) ? 10 : input('pageSize');
        $admin = session('admin');
        $admin = AdminModel::get(['id' => $admin['id']]);
        $where = array();
        if ($admin['is_super'] != 1) {
            $where['is_delete'] = 0;
        }
        if (!empty($keyword)) {
            $where['title|title_en|title_as'] = array('like', '%' . $keyword . '%');
        }
        if (!empty($project_id)) {
            $where['project_id'] = $project_id;
        }
        if ($isShowExpire == 0 || $isShowExpire == '') {
            $where['endtime'] = array('EGT', date('Y-m-d', time()));
        }
        if (!empty($startTime) && !empty($endTime)) {
            // $startTime=strtotime($startTime);
            // $endTime=strtotime($endTime);
            $where['starttime'] = array('egt', $startTime);
            $where['endtime'] = array('elt', $endTime);
        }

        // 11
//        $com=new commonplus();
//        $tbname2= "exhibition"; // 表名称
//        $where2=array('id'=>'22');
//        $res=$com->sel_com_one('none', $where2, $tbname2); // 查询某信息
//        var_dump($res['title']);die;

        // 3
        //  var_dump($where);die;
        $list = db('exhibition')
            ->where($where)
            ->order('sort asc')
            ->limit(($page - 1) * $pagesize . ',' . $pagesize)
            ->select();
        $total = db('exhibition')
            ->where($where)
            ->count();
        foreach ($list as &$v){
            $tabTotal=$v['create_tablename']?db($v['create_tablename'])->count():0;
            $v['is_add_data']=$tabTotal;
        }
        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list, 'count' => $total]]);
    }

    /**
     * 条件查询展会
     */
    public function getListByCon()
    {
        $keyword = $this->request->param('keyword');
        $project_id = $this->request->param('project_id');

        $page = $this->request->param('page');

        $page = max(1, intval($page));
        $pagesize = 10;

        $where['is_delete'] = 0;
        if (!empty($keyword)) {
            $where['title|title_en|title_as'] = array('like', '%' . $keyword . '%');
        }

        if (!empty($project_id)) {
            $where['project_id'] = $project_id;
        }

        $where['endtime'] = array('EGT', date('Y-m-d', time()));

        $list = $this->model->listWherePage($where, 'id desc', ($page - 1) * $pagesize, $pagesize);
        $total = $this->model->countWhere($where);

        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list, 'count' => $total]]);
    }

    /**
     * 展会详情
     * @return \think\response\Json|void
     */
    public function detail()
    {
        $id = $this->request->param('id');

        $where['id'] = $id;
        $where['is_delete'] = 0;
        $info = $this->model->findWhere($where);

        #展会信息

        return json(['code' => 1, 'msg' => 'success', 'data' => $info]);
    }

    /**
     * 删除展会
     * @return \think\response\Json|void
     */
    public function del()
    {
        $ids = $this->request->param('id');
        $id = explode(',', $ids);
        $is = true;
        //首先进行数据验证
        foreach ($id as $val) {
            $where = ['id' => ['in', $val]];
            $r = $this->model->countWhere($where);
            if (empty($r)) {
                $is = false;
                break;
            }
        }
        if (!$is) {
            return json(['code' => 0, 'msg' => '记录不存在，请核实']);
        }
        $msg = '';
        foreach ($id as $v) {
            $exRes = $this->model->findWhere(['id' => $v]);
            $r = $this->model->updateBywhere(['is_delete' => ($exRes['is_delete'] == 0 ? 1 : 0)], ['id' => $v]);
            if (!$r) {
                $is = false;
                $msg = 'id:' . $v . '操作失败';
            }
        }

        if (!$is) {
            Db::rollback();
            return json(['code' => 0, 'msg' => $msg]);
        }
        Db::commit();
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     *
     * @return mixed
     */
    public function _before_add()
    {
        $data['title'] = $this->request->param('title');
        $data['title_en'] = $this->request->param('title_en');
        $data['title_as'] = $this->request->param('title_as');
        $data['project_id'] = $this->request->param('project_id');
        $data['industry_id'] = $this->request->param('industry_id');
        $data['starttime'] = $this->request->param('starttime');
        $data['endtime'] = $this->request->param('endtime');
        $data['city'] = $this->request->param('city');
        $data['category_id'] = $this->request->param('category_id');
        $data['customer_manager'] = $this->request->param('customer_manager');
        $data['questionnaire_id'] = $this->request->param('questionnaire_id');
        $data['is_company'] = $this->request->param('is_company');
        $data['merchants_manager'] = $this->request->param('merchants_manager');
        $data['merchants_group'] = $this->request->param('merchants_group');
        $data['exhibition_level'] = $this->request->param('exhibition_level');
        $data['is_exhibition'] = $this->request->param('is_exhibition');
        $login_strat_time = $this->request->param('login_strat_time');
        $login_end_time = $this->request->param('login_end_time');
        $data['login_strat_time'] = strtotime($login_strat_time . "  00:00:00");
        $data['login_end_time'] = strtotime($login_end_time . "  23:59:59");
        $data['home_like'] = $this->request->param('home_like');
        $data['pic'] = $this->request->param('pic');
        $data['is_open_register'] = $this->request->param('is_open_register');
        $data['register_info'] = $this->request->param('register_info');
        $data['header_logo'] = $this->request->param('header_logo');
        $data['server_phone'] = $this->request->param('server_phone');
        $data['server_email'] = $this->request->param('server_email');
        $data['exhibition_address'] = $this->request->param('exhibition_address');
        $data['hall_bg'] = $this->request->param('hall_bg');
        $data['hall_bg'] = $this->request->param('hall_bg');
        $data['header_logo_mobile'] = $this->request->param('header_logo_mobile');
        $data['company_banner'] = $this->request->param('company_banner');
        $data['ticket_amount'] = $this->request->param('ticket_amount');
        $data['card_amount'] = $this->request->param('card_amount');
        $data['card_voucher'] = $this->request->param('card_voucher');
        $data['appid'] = $this->request->param('appid');
        return $data;
    }

    /**
     * 增加展会
     * @return \think\response\Json|void
     *  记录新表 create_tablename，
     *  动态表名 要唯一 ，影响后期新表； 2：有些人信息误删？禁止删除；3：如果需要修改 联系管理员
     */
    public function add(){
        $com=new commonplus();
        $data = $this->_before_add();
        $data['create_time']  = time();
        $data['update_time']  = time();
        $data['is_delete']  = 0;
        // 建表检测项
        if($data['title']=="" || $data['title_en']==""){
            return json(['code'=>0,'msg'=>'展商名称或者展会英文不能为空!']);
        }
        $where1 = array('title' => $data['title']);
        $r1 = $com->sel_com_fxlist("f", $where1, "Exhibition");
        if($r1){
            return json(['code'=>0,'msg'=>'展商名称重复']);
        }
        $where1 = array('title_en' => $data['title_en']);
        $r1 = $com->sel_com_fxlist("f", $where1, "Exhibition");
        if($r1){
            return json(['code'=>0,'msg'=>'展会英文重复']);
        }

        //$qz='zh_'.date('YmdHis').rand(111, 999);
        // 执行建表 ，表规则不能横线- _
        //$tbnewname='zh_'.date('Ymd').strtolower($data['title_en']);
        $tbnewname='zh_'.date('YmdHis');
        //if($r1['create_tablename']==""){
        // 检测是否已建 好像每次都是新 。待观察,复制模版表
        $para=array('tbname'=>$tbnewname,'oldtbname'=>'crm_zh_0000model_fmr_2020');
        //$re=$com->createtable_zh('11',$para);
        $re=$com->createtable_zh_bymodel('zh',$para);
        if(!$re){
            return json(['code'=>0,'msg'=>'建表环节有误-展商表']);
        }
        //  }
        // 建立个人动态表 st 200817
        $tbnewname_per='zh_'.date('YmdHis')."_per";
        $para=array('tbname'=>$tbnewname_per,'oldtbname'=>'crm_zh_0000model_fmr_2020_per');
        //$re=$com->createtable_zh_person('11',$para);
        $re=$com->createtable_zh_bymodel('per',$para);
        if(!$re){
            return json(['code'=>0,'msg'=>'建表环节有误-个人表']);
        }

        // zxjb ed
        $data['create_tablename']  = $tbnewname;
        $data['create_person_table']  = $tbnewname_per;//人员动态表
        $r = $this->model->insertData($data);

        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 编辑展会
     * @return \think\response\Json|void
     */
    public function edit(){
        $id = $this->request->param('id');
        $data = $this->_before_add();
        $data['update_time']  = time();

        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数有误，请核查']);
        }

        $where['id'] = $id;
        $r = $this->model->updateBywhere($data,$where);

        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 展会分类列表
     */
    public function typeList(){
        $list = db('exhibition_type')->where('is_delete',0)->select();
        return json(['code'=>1,'msg'=>'success','data'=>$list]);;
    }

    /**
     * 增加展会分类
     * @return \think\response\Json|void
     */
    public function addType(){
        $title = $this->request->param('title');
        $r = db('exhibition_type')->insertGetId(['title'=>$title]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 编辑展会分类
     * @return \think\response\Json|void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editType(){
        $id = $this->request->param('id');
        $title = $this->request->param('title');
        $r = db('exhibition_type')->where('id',$id)->update(['title'=>$title]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 删除展会类型
     * @return \think\response\Json|void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delType(){
        $id = $this->request->param('id');
        $r = db('exhibition_type')->where('id',$id)->update(['is_delete'=>1]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }



    /**
     * 获取展会下所有展厅
     */
    public function getAllHall(){
        $id = input('id');
        if(empty($id)){
            return json(['code'=>1,'msg'=>'参数有误']);
        }
        $list = db('hall')->alias('a')->field('a.*')->join('pavilion b','a.pavilion_id=b.id','left')->where('b.exhibition_id',$id)->select();
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }

    /**
     * 查看管理员
     *
     * @return void
     */
    public function index()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $orgId = isset($post['org_id']) && $post['org_id'] != '' ? $post['org_id'] : 0;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
            $where['is_super'] = 0;
            if ($orgId != 0) {
                // $where['a.org_id'] = $orgId;
                $where[] = ['exp', Db::raw('FIND_IN_SET(' . $orgId . ',a.org_id_tree)')];
            }
            if (isset($post['keyword']) && $post['keyword'] != '') {
                $where['a.account|a.realname'] = ['like', '%' . $post['keyword'] . '%'];
            }
            $adminList = AdminModel::alias('a')
                ->with('role')
                ->join('crm_organization b', 'b.id = a.org_id', 'LEFT')
                ->where($where)
                ->field('a.id,a.account,a.realname,a.mobile,a.email,a.org_id,b.org_name,a.create_time,a.update_time')
                ->paginate($pageSize);
            $list = $adminList->toArray();
            unset($list['per_page'], $list['last_page']);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $list));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    /**
     * 排序
     *
     * @return void
     */
    public function setSore()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $ids = isset($post['ids']) && $post['ids'] != '' ? $post['ids'] : '';
            if (!$ids) {
                return json(array('code' => '0', 'msg' => '信息错误'));
            }
            $ids=explode(",", $ids);
            $num=0;
            foreach ($ids as $v){
                $num++;
                db('exhibition')->where(['id'=>$v])->update(['sort'=>$num]);
            }
            return json(array('code' => '1', 'msg' => '成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    /**
     * 增加公海数据
     *
     * @return void
     */
    public function setAddWater()
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;//待添加
                $exhibition_id1 = isset($post['exhibition_id1']) && $post['exhibition_id1'] != '' ? $post['exhibition_id1'] : 0;//源数据
                $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
                if(!$exhibition){
                    return json(['code'=>0,'msg'=>'展会信息错误']);
                }
                $exhibition1=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id1])->find();
                if(!$exhibition1){
                    return json(['code'=>0,'msg'=>'数据源展会信息错误']);
                }
                $total=db($exhibition['create_tablename'])->count();
                if($total>0){
                    return json(['code'=>0,'msg'=>'添加展会数据库已有数据!']);
                }
                $total1=db($exhibition1['create_tablename'])->count();
                if($total1 == 0){
                    return json(['code'=>0,'msg'=>'数据源展会数据库为空!']);
                }
                #开始复制数据
                $sql="insert into crm_".$exhibition['create_tablename'];
                $sql.="(company_name,company_address,company_address_en,link,contact,positions,company_name_en,tel,product,mobile,email,category_id,second_category_id,country_code,country,area,province,area_city,area_town,data_from,industrys,name_cn,name_en,positions_cn,positions_en,department_cn,department_en,chau,company_id1,logo,is_chukou,country_chukou,is_card_sheng,info_card_sheng,isdoselfbrander,doselfbrander_info,comfrom,sale_id,member_id,info_card_logo,quality_system,quality_system_zheng,Issue_on_behalf,edit_logo,create_time,update_time) select ";
                $sql.="  company_name,company_address,company_address_en,link,contact,positions,company_name_en,tel,product,mobile,email,category_id,second_category_id,country_code,country,area,province,area_city,area_town,data_from,industrys,name_cn,name_en,positions_cn,positions_en,department_cn,department_en,chau,company_id1,logo,is_chukou,country_chukou,is_card_sheng,info_card_sheng,isdoselfbrander,doselfbrander_info,comfrom,sale_id,member_id,info_card_logo,quality_system,quality_system_zheng,Issue_on_behalf,edit_logo,".time().",".time();
                $sql.="  from crm_".$exhibition1['create_tablename'];
                $res=Db::query($sql);
                if(false === $res){
                    return json(['code'=>0,'msg'=>'操作失败']);
                }
                #开始重置保护时间、更新时间、展商状态  status
                $resMember=db($exhibition['create_tablename'])->where(['member_id'=>array('egt',0)])->update(['status'=>1,'protection_time'=>time()]);
                if(false === $resMember){
                    return json(array('code' => '1', 'msg' => '保护时间失败'));
                }

                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }



    /**
     * 展会小程序编辑
     *is_wechat: this.is_wechat,
    wechat_name: this.wechat_name,
     * @return void
     */
    public function wechat()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;//待添加
            $is_wechat = isset($post['is_wechat']) && $post['is_wechat'] != '' ? $post['is_wechat'] : 0;//源数据
            $wechat_name = isset($post['wechat_name']) && $post['wechat_name'] != '' ? $post['wechat_name'] : null;//源数据
            $wechat_channel_id = isset($post['wechat_channel_id']) && $post['wechat_channel_id'] != '' ? $post['wechat_channel_id'] : 0;//源数据
            $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
            if(!$exhibition){
                return json(['code'=>0,'msg'=>'展会信息错误']);
            }
            $channel=db('zsqudao')->where(['id'=>$wechat_channel_id,'is_delete'=>0])->find();
            if(!$channel){
                return json(['code'=>0,'msg'=>'渠道id错误']);
            }
            $data['is_wechat']=$is_wechat;
            $data['wechat_name']=$wechat_name;
            $data['wechat_channel_id']=$wechat_channel_id;
//            var_dump($data);die();
            $res=db('exhibition')->where(['id'=>$exhibition_id])->update($data);
            if(false === $res){
                return json(['code'=>0,'msg'=>'操作失败']);
            }
            return json(array('code' => '1', 'msg' => '成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    /**
     * 展会信息
     * @return \think\response\Json|void
     *  记录新表 create_tablename，
     *  动态表名 要唯一 ，影响后期新表； 2：有些人信息误删？禁止删除；3：如果需要修改 联系管理员
     */
    public function addInfo(){
        if (request()->isPost()) {
            $post = input('post.');
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$id])->find();
            if(!$exhibition){
                return json(['code'=>0,'msg'=>'展会信息错误']);
            }
            $data['start_year'] = isset($post['start_year']) && $post['start_year'] != '' ? $post['start_year'] : null;
            $data['organizer'] = isset($post['organizer']) && $post['organizer'] != '' ? $post['organizer'] : null;
            $data['hotel'] = isset($post['hotel']) && $post['hotel'] != '' ? $post['hotel'] : null;
            $data['traffic'] = isset($post['traffic']) && $post['traffic'] != '' ? $post['traffic'] : null;
            $data['describe'] = isset($post['describe']) && $post['describe'] != '' ? $post['describe'] : null;
            $data['update_time']=time();
            $res=db('exhibition')->where(['id'=>$id])->update($data);
            if(false === $res){
                return json(['code'=>0,'msg'=>'操作失败']);
            }
            return json(array('code' => '1', 'msg' => '成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


}